package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.dromara.basic.service.IDictService;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysDictData;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.system.domain.bo.SysDictDataBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.mapper.SysDictDataMapper;
import org.dromara.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysDictDataServiceImpl implements ISysDictDataService , IDictService {

    private final SysDictDataMapper baseMapper;

    @Override
    public TableDataInfo<SysDictDataVo> selectPageDictDataList(SysDictDataBo dictData, PageQuery pageQuery) {
        LambdaQueryWrapper<SysDictData> lqw = buildQueryWrapper(dictData);
        Page<SysDictDataVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictDataVo> selectDictDataList(SysDictDataBo dictData) {
        LambdaQueryWrapper<SysDictData> lqw = buildQueryWrapper(dictData);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysDictData> buildQueryWrapper(SysDictDataBo bo) {
        LambdaQueryWrapper<SysDictData> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDictSort() != null, SysDictData::getDictSort, bo.getDictSort());
        lqw.like(StringUtils.isNotBlank(bo.getDictLabel()), SysDictData::getDictLabel, bo.getDictLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getDictType()), SysDictData::getDictType, bo.getDictType());
        lqw.orderByAsc(SysDictData::getDictSort);
        return lqw;
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysDictData>()
                .select(SysDictData::getDictLabel)
                .eq(SysDictData::getDictType, dictType)
                .eq(SysDictData::getDictValue, dictValue))
            .getDictLabel();
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictDataVo selectDictDataById(Long dictCode) {
        return baseMapper.selectVoById(dictCode);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData data = baseMapper.selectById(dictCode);
            baseMapper.deleteById(dictCode);
            CacheUtils.evict(CacheNames.SYS_DICT, data.getDictType());
        }
    }

    /**
     * 新增保存字典数据信息
     *
     * @param bo 字典数据信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.dictType")
    @Override
    public List<SysDictDataVo> insertDictData(SysDictDataBo bo) {
        SysDictData data = MapstructUtils.convert(bo, SysDictData.class);
        int row = baseMapper.insert(data);
        if (row > 0) {
            return baseMapper.selectDictDataByType(data.getDictType());
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 修改保存字典数据信息
     *
     * @param bo 字典数据信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.dictType")
    @Override
    public List<SysDictDataVo> updateDictData(SysDictDataBo bo) {
        SysDictData data = MapstructUtils.convert(bo, SysDictData.class);
        int row = baseMapper.updateById(data);
        if (row > 0) {
            return baseMapper.selectDictDataByType(data.getDictType());
        }
        throw new ServiceException("操作失败");
    }

    @Override
    public String getDictName(String dictType, String dictCode,String tenantId) {
        LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<SysDictData>();
        queryWrapper.select(SysDictData::getDictLabel);
        queryWrapper.eq(SysDictData::getDictType, dictType);
        queryWrapper.eq(SysDictData::getDictValue, dictCode);
        queryWrapper.eq(SysDictData::getTenantId,tenantId);
        SysDictData sysDictData = baseMapper.selectOne(queryWrapper);
        return ObjectUtils.isNotEmpty(sysDictData)?sysDictData.getDictLabel():null;
    }
    @Override
    public String getDictValue(String dictType, String dictLabel,String tenantId) {
        LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<SysDictData>();
        queryWrapper.select(SysDictData::getDictLabel);
        queryWrapper.eq(SysDictData::getDictType, dictType);
        queryWrapper.eq(SysDictData::getDictLabel, dictLabel);
        queryWrapper.eq(SysDictData::getTenantId,tenantId);
        SysDictData sysDictData = baseMapper.selectOne(queryWrapper);
        return ObjectUtils.isNotEmpty(sysDictData)?sysDictData.getDictLabel():null;
    }
    public boolean insertDict(Map<String,String> gradeMap,String tenantId,String dictType){

        if(!gradeMap.isEmpty()){
            for (Map.Entry<String, String> entry : gradeMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                SysDictData sysDictData=new SysDictData();
                sysDictData.setDictType(dictType);
                sysDictData.setDictValue(key);
                sysDictData.setDictLabel(value);
                sysDictData.setDictSort(0);
                sysDictData.setTenantId(tenantId);
                LambdaQueryWrapper<SysDictData> lqw = Wrappers.lambdaQuery();
                lqw.eq(SysDictData::getDictType,dictType);
                lqw.eq(SysDictData::getDictValue,key);
                lqw.eq(SysDictData::getTenantId,tenantId);
                SysDictData sysDictData1 = baseMapper.selectOne(lqw);
                if(ObjectUtils.isNotEmpty(sysDictData1)){
                    sysDictData.setDictCode(sysDictData1.getDictCode());
                    baseMapper.updateById(sysDictData);
                }else {
                    baseMapper.insert(sysDictData);
                }
            }
        }
        return true;
    }
    public Map<String,String> selectAll(String tenantId,String dictType){
        LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<SysDictData>();
        queryWrapper.eq(SysDictData::getTenantId,tenantId).eq(SysDictData::getDictType,dictType);
        List<SysDictData> sysDictData = baseMapper.selectList(queryWrapper);
        Map<String, String> resultMap =new HashMap<>();
        if(CollectionUtils.isNotEmpty(sysDictData)){
            resultMap=sysDictData.stream()
                .collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        }
        return resultMap;
    }

    @Override
    public List<String> getDictValue(String dictType) {
        List<SysDictDataVo> sysDictData = baseMapper.selectVoList(new LambdaQueryWrapper<SysDictData>()
            .select(SysDictData::getDictValue)
            .eq(SysDictData::getDictType, dictType));
        return CollectionUtils.isNotEmpty(sysDictData)?sysDictData.stream()
            .map(SysDictDataVo::getDictValue)
            .collect(Collectors.toList()):new ArrayList<>();
    }
}
